<?php
namespace Common\Controller;

Trait ApiTrait  
{  
    /**
     +----------------------------------------------------------
     * Ajax方式返回数据到客户端
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param boolean $status 返回状态
     * @param mixed $data 要返回的数据
     * @param String $info 提示信息
     * @param String $status ajax返回类型 JSON XML
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
    public function ajaxReturn($status=1,$data,$info='',$type='')
    {
        // 保证AJAX返回后也能保存日志
        $data = $this->filter_null($data);

        if($status!==1 && empty($data)){
            $data=null;
        }

        $result  =  array();
        $result['status']  =  $status;
        $result['message'] =  $info;
        $result['data'] = $data;
        if(APP_DEBUG){
//            //log_debug(json_encode($result));
//            log_debug(
//                "\n----------------------getparams----------------------\n".var_export($_GET,true)."\n"."----------------------postparams----------------------\n".var_export($_POST,true)."\n"."-----------ajaxReturn--------\r\n".stripslashes($this->convertUnicode($this->jsonFormat($result)))
//                ."\r\n");
        }
        if(empty($type)) $type  =   "JSON";
        if(strtoupper($type)=='JSON') {
            // 返回JSON数据格式到客户端 包含状态信息
            header("Content-Type:text/html; charset=utf-8");
            exit(json_encode($result));
        }elseif(strtoupper($type)=='XML'){
            // 返回xml格式数据
            header("Content-Type:text/xml; charset=utf-8");
            exit(xml_encode($result));
        }elseif(strtoupper($type)=='EVAL'){
            // 返回可执行的js脚本
            header("Content-Type:text/html; charset=utf-8");
            exit($data);
        }else{
            // TODO 增加其它格式
        }
    }
    
    function convertUnicode($content){
        return preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $content);
    }
    
    function jsonFormat($data, $indent=null){
        // 对数组中每个元素递归进行urlencode操作，保护中文字符
        array_walk_recursive($data, 'jsonFormatProtect');
        // json encode
        $data = json_encode($data);
        // 将urlencode的内容进行urldecode
        $data = urldecode($data);
        // 缩进处理
        $ret = '';
        $pos = 0;
        $length = strlen($data);
        $indent = isset($indent)? $indent : '    ';
        $newline = "\n";
        $prevchar = '';
        $outofquotes = true;
    
        for($i=0; $i<=$length; $i++){
            $char = substr($data, $i, 1);
            if($char=='"' && $prevchar!='\\'){
                $outofquotes = !$outofquotes;
            }elseif(($char=='}' || $char==']') && $outofquotes){
                $ret .= $newline;
                $pos --;
                for($j=0; $j<$pos; $j++){
                    $ret .= $indent;
                }
            }
            $ret .= $char;
            if(($char==',' || $char=='{' || $char=='[') && $outofquotes){
                $ret .= $newline;
                if($char=='{' || $char=='['){
                    $pos ++;
                }
                for($j=0; $j<$pos; $j++){
                    $ret .= $indent;
                }
            }
            $prevchar = $char;
        }
        return $ret;
    }
    
    /**
     * 中文截取无乱码
     */
    public function sub($str, $from, $len){
        return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
            '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
            '$1',$str);
    }
    
    public function filter_null($data){
        if(empty($data) || !is_array($data)){
            return $data;
        }
    
        $data = (array)$data;
        foreach($data as $key => $info){
            if(is_array($info)){
                foreach($info as $k => $in){
                    if(is_array($in)){
                        foreach($in as $k1 => $in1){
                            $in1 = is_null($in1) ? "" : $in1;
                            $in[$k1] = $in1;
                        }
                    }
                    $in = is_null($in) ? "" : $in;
                    $info[$k] = $in;
                }
            }
            $info = is_null($info) ? "" : $info;
            $data[$key] = $info;
        }
    
        return $data;
    }

    public function page($total_size = 1, $page_size = 20, $current_page = 1
        , $listRows = 6, $pageParam = '', $pageLink = '', $static = false) {
        if ($page_size == 0) {
            $page_size = C("PAGE_LISTROWS");
        }

        if (empty($pageParam)) {
            $pageParam = "page";
        }

        $page = new \Pager
        ($total_size, $page_size, $current_page, $listRows, $pageParam, $pageLink, $static);

        return $page;
    }

}  